package com.yc.junit;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;

public class TestRunner {

    public static void main(String[] args)
            throws Exception {
        Class[] testerCLasses = {MathBizTest.class};
        for (Class testerClass : testerCLasses) {
            // 创建被测试对象 => new XXX();
            Object tester = testerClass.newInstance();
            // 全部共有方法
            Method[] methods = testerClass.getMethods();
            List<Method> testMethods = new ArrayList<>();
            // 收集测试方法
            for (Method method : methods) {
                if(method.getAnnotation(Test.class) != null){
                    testMethods.add(method);
                }
            }

            //排序 TODO
//            testMethods.sort(new Comparator<Method>() {
//                @Override
//                public int compare(Method o1, Method o2) {
//                    Test test1 = o1.getAnnotation(Test.class);
//                    Test test2 = o2.getAnnotation(Test.class);
//                    return test1.value() - test2.value();
//                }
//            });
//
//            testMethods.sort((o1, o2) -> {
//                Test test1 = o1.getAnnotation(Test.class);
//                Test test2 = o2.getAnnotation(Test.class);
//                return test1.value() - test2.value();
//            });

            testMethods.sort((o1, o2) -> o1.getAnnotation(Test.class).value() - o2.getAnnotation(Test.class).value());

            // 执行测试
            int success = 0; // 正常
            int failure = 0; // 断言错误
            int errors = 0;  // 测试方法出现异常
            for (Method testMethod : testMethods) {
                try{
                    testMethod.invoke(tester);
                    success ++;
                } catch (InvocationTargetException e){
                    Throwable cause = e.getCause();
                    if(cause instanceof AssertionError){
                        failure ++;
                    } else {
                        errors ++;
                    }
                }
            }
            System.out.println("测试成功: " + success);
            System.out.println("测试失败: " + failure);
            System.out.println("测试错误: " + errors);

            // TODO 请实现 Before 和 After 注解
        }

    }

}
